package com.example.mytestapp.testvideoplayer;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import com.example.mytestapp.MainActivity;
import com.example.mytestapp.R;

import java.io.IOException;

public class TestVieoPlayActivity extends Activity implements SurfaceHolder.Callback{
    private SurfaceView surfaceView = null;
    private SurfaceHolder surfaceHolder = null;
    private MediaPlayer mMediaPlayer = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_vieo_play);

        surfaceView = findViewById(R.id.sufaceview);
        surfaceView.getHolder().addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        this.surfaceHolder = surfaceHolder;

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch (keyCode){
                case KeyEvent.KEYCODE_0:
                    if(mMediaPlayer == null){
                        mMediaPlayer = new MediaPlayer();
                    }
                    //mMediaPlayer.reset();
                    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
                    mMediaPlayer.setDisplay(surfaceHolder);
                    try {
                        mMediaPlayer.setDataSource("rtsp://192.168.10.205:554/SubStream");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mMediaPlayer.prepareAsync();
                    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            if (mMediaPlayer != null) {
                                mMediaPlayer.start();
                            }
                        }
                    });
                    mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                            return false;
                        }
                    });

                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
